#include "common.h"

int main(int argc, char* argv[]) {

	int sock_serv; // listening socket
	int sockfd; // connection socket
	short int port; //port number
	struct sockaddr_in servaddr; // socket address struct
	char buffer[MAXBUF]; // character buffer
	char *endptr;  // for strtol ()
	int tr = 1, i=0, size=0,num=0, k=0;
	fd_set active_fd_set, tmpfds;
	//int ser_num=0;


	client_t client[MAX_CLIENTS];


	for (num = 0; num<MAX_CLIENTS; num++){
		client[num].fd = 0;
		client[num].pseudo = NULL;
		client[num].type = 0;
	}
	/* Get port number from the command line , and set to default port if
     no arguments were supplied
	 */

	if ( argc >= 2 ) {
		port = strtol(argv[1], &endptr, 0);
		if ( *endptr ) {
			fprintf(stderr, "ECHOSERV: Invalid port number.\n");
			exit(EXIT_FAILURE);
		}
		//ser_num = atoi(argv[2]);
	}
	else if ( argc < 2 ) {
		port = PORT;
	}
	else {
		fprintf(stderr, "ECHOSERV: Invalid arguments.\n");
		exit(EXIT_FAILURE);
	}

	/* Create the listening socket */

	if ( (sock_serv = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
		fprintf(stderr, "ECHOSERV: Error creating listening socket.\n");
		exit(EXIT_FAILURE);
	}

	/*Set all bytes in socket address structure to zero,
    and fill in the relevant data members */

	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(port);



	/* Bind our socket address to the listening socket,
     and call listen()*/
	if (setsockopt(sock_serv,SOL_SOCKET,SO_REUSEADDR,&tr,sizeof(int)) == -1) {
		perror("setsockopt");
		exit(1);
	}
	if ( bind(sock_serv, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 ) {
		fprintf(stderr, "ECHOSERV: Error calling bind()\n");
		exit(EXIT_FAILURE);
	}

	if ( listen(sock_serv, LISTENQ) < 0 ) {
		fprintf(stderr, "ECHOSERV: Error calling listen()\n");
		exit(EXIT_FAILURE);
	}

	/* FD_ZERO() clears out the different fdsets, so that
     it doesn't contain any file descriptors.*/

	FD_ZERO (&active_fd_set);
	FD_SET (sock_serv, &active_fd_set);


	/*We initially have only one socket open, to receive new
    incoming connections. Initialise accordingly the tmpfds
    set with select MACRO*/



	/* Enter an infinite loop to respond to client requests and echo input*/
	// a socket to connect to a 2nd server.
	/*if (ser_num > 1){
		FILE* fp, fp2;

		char filename_o[] = "/home/karim/workspace_1/RE216/bin/servers_log1.txt";
		// creating the file
		fp = fopen(filename_o, "a+");

		fp = fopen(filename_o, "a+");
		char filename[] = "/home/karim/workspace_1/RE216/bin/servers_log";
		char* filename2 = NULL;
		filename2 = malloc(8*sizeof(char));
		sprintf(filename2, "%s.txt", argv[2]);
		strcat(filename, filename2);
	}
	 */
	int choice = 0;
	char* ip2 = NULL;
	ip2 = malloc(sizeof(char)* 20);
	char* port2 = NULL;
	port2 = malloc(sizeof(char)* 20);
	int* server_sock[SERVERS];
	for (i=0; i < SERVERS; i++){
		server_sock[i] = NULL;
		server_sock[i] = malloc(sizeof(int));
	}

	char server_adv[] = "MSE\n";

	printf("Serveur:\n");
	while ( choice != 2) {
		printf("1. Connection à un serveur.\n");
		printf("2. Accepter les connections de clients.\n");
		scanf("%d", &choice);

		switch (choice){
		case 1 :
			printf("Donner l'adresse IP du serveur\n");
			scanf("%s", ip2);
			printf("Donner le port du serveur\n");
			scanf("%s", port2);
			create_socket_connect(ip2, port2, server_sock[atoi(argv[2])-2]);
			printf("Hello after connect function\n");
			Sendline(*server_sock[atoi(argv[2])-2], server_adv, strlen(server_adv));
			break;
		case 2 :
			printf("Accepting connections ...\n");
			break;
		default:
			printf("Le caractère que vous avez entré n'est pas valide\n");
			printf("Réessayez!\n");
			break;
		}
	}

	printf("Attente de connexion\n");

	int max = sock_serv;
	while (1) {
		tmpfds = active_fd_set;
		if (select(max+1, &tmpfds, NULL, NULL, NULL) < 0)
		{
			perror ("select");
			exit (EXIT_FAILURE);
		}

		/* calculate size of file descriptors table*/


		/* The select() system call waits until any of the file descriptors
       specified in the read, sets given to it, is ready to give data */

		for (i = 3; i <= max; ++i) {
			if (FD_ISSET (i, &tmpfds)) {
				if (i == sock_serv) {
					/* Connection request on original socket. */
					size = sizeof (servaddr);
					sockfd = accept (sock_serv, (struct sockaddr *) &servaddr,
							(socklen_t *) &size);
					if (sockfd < 0)
					{
						perror ("accept");
						exit (EXIT_FAILURE);
					}
					fprintf (stderr,"Server: connect from host %s, port %d.\n",
							inet_ntoa(servaddr.sin_addr),
							(int) ntohs (servaddr.sin_port));
					FD_SET (sockfd, &active_fd_set);

					if(sockfd > max) max = sockfd;
				}



				/*Make the difference between a new client connection and data
      	  receveid from an already existing client*/
				else
				{	/* Ask for a nickname ... */
					if (client[i].fd == 0){
						client[i].fd = i;
					}
					/* Data arriving on an already-connected socket. */

					/* SERVERS AVAILABLE */

					Readline(i, buffer, MAXBUF-1);




					if (buffer[0] == 'M' && buffer[1] == 'S' && buffer[2] == 'E' ){
						client[i].type = 1;

						for (k=0; k< max+1; k++){
							if (client[k].type !=0){
								printf("A server is connected\n");
							}
						}
						for (k=0; k < atoi(argv[2])-1; k++){
							printf("A server is connected\n");
						}
					}


					if (buffer[0] == 'C' && buffer[1] == 'L' && buffer[2] == 'T' ){
						client[i].type = 2;

						printf("A client is connected.\n");
						strcpy(buffer, &(buffer[3]));
						printf("%s", buffer);



					}


					/* INIT CLIENT */
					/* Specific work FOR every client. */
					/* Ask visitor or member */

					/* Ask for a nickname */
					/* Ask for password if member */

					/* PROPOSE MENU TO: */

					/* Enable client to : */
					/* get list of connected clients */
					/* create a group of people && check whether it is unique */
					/* get list of created groupes */
					/* join an existing groupe */
					/* send a message to groupe he belongs to  */
					/* enable a master of a group to ban a client  */
					/* Register. Info should be stored in a file! */

					/* EVENTS HANDLING */
					/* Broadcast events : connexion && deconnection */
					// => Broadcast it to servers and clients
					// Servers should update their clients' table
					/* Broadcast events : sign-up */
					// => Broadcast it to servers only !
					// Servers should update their clients' file

				}

			}
		}

	} // END OF WHILE

}



